package cn.yzgy.yzgyoa.ucenter.controller;


import cn.yzgy.yzgyoa.common.annotation.ApiDesc;
import cn.yzgy.yzgyoa.common.constant.YzCacheName;
import cn.yzgy.yzgyoa.common.controller.BaseController;
import cn.yzgy.yzgyoa.common.crsp.StatusCode;
import cn.yzgy.yzgyoa.common.crsp.Urmf;
import cn.yzgy.yzgyoa.common.exception.SystemException;
import cn.yzgy.yzgyoa.common.utils.YzCacheHelper;
import cn.yzgy.yzgyoa.common.utils.ToolsUtil;
import cn.yzgy.yzgyoa.ucenter.dto.RoleDTO;
import cn.yzgy.yzgyoa.ucenter.entity.SysRole;
import cn.yzgy.yzgyoa.ucenter.entity.SysRolePermission;
import cn.yzgy.yzgyoa.ucenter.entity.SysUser;
import cn.yzgy.yzgyoa.ucenter.service.ISysPermissionService;
import cn.yzgy.yzgyoa.ucenter.service.ISysRolePermissionService;
import cn.yzgy.yzgyoa.ucenter.service.ISysRoleService;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用户角色表 前端控制器
 * </p>
 *
 * @author Yqsen
 * @since 2019-12-10
 */
@RestController
@RequestMapping("/ucenter/sys-role")
public class SysRoleController extends BaseController {

    private final ISysRoleService iSysRoleService;
    private final ToolsUtil toolsUtil;
    private final ISysRolePermissionService iSysRolePermissionService;
    private final ISysPermissionService iSysPermissionService;
    private final YzCacheHelper yzCacheHelper;

    @Autowired
    public SysRoleController(ISysRoleService iSysRoleService,
                             ToolsUtil toolsUtil,
                             ISysRolePermissionService iSysRolePermissionService,
                             ISysPermissionService iSysPermissionService,
                             YzCacheHelper yzCacheHelper
                             ) {
        this.iSysRoleService = iSysRoleService;
        this.toolsUtil = toolsUtil;
        this.iSysRolePermissionService = iSysRolePermissionService;
        this.iSysPermissionService = iSysPermissionService;
        this.yzCacheHelper = yzCacheHelper;
    }

    /**
     * 分页获取role列表数据
     * @param page 数据页
     * @param size 数据条数
     * @return 数据页
     */
    @ApiDesc(value = "获取SysRole数据列表",log = true)
    @GetMapping("/queryAllRole")
    @RequiresPermissions("api:role:data:get")
    public Object queryAllArea(String page,String size){
        //获取roleDto对象数据
        IPage<RoleDTO> ipageRoleDTO = new Page<>(Integer.parseInt(page), Integer.parseInt(size));
        Integer num = (Integer.parseInt(page)-1)*Integer.parseInt(size);
        Object roleDtoIpage = iSysRoleService.queryAllRoleDTO(ipageRoleDTO,num, Integer.parseInt(size));
        String total = iSysRoleService.countData();
        //获取sysrole对象数据组装页面
        IPage<SysRole> ipageSysRole = new Page<>(Integer.parseInt(page), Integer.parseInt(size));
        QueryWrapper<SysRole> wrapper = new QueryWrapper<>();
        Object roleIpage = iSysRoleService.queryAll(ipageSysRole, wrapper);
        //将roleDto注入sysrole的页面 偷天换日
        ((IPage) roleIpage).setRecords(((IPage) roleDtoIpage).getRecords());
        ((IPage) roleIpage).setTotal(Long.parseLong(total));
        return Urmf.success("获取SysRole数据列表", StatusCode.SUCCESS,roleIpage);
    }

    /**
     * 修改角色相关数据
     * @param roleInfo 角色对象
     * @return 成功状态
     */
    @ApiDesc(value = "修改角色相关信息",log = true)
    @PutMapping("/changeInfo")
    @RequiresPermissions("api:role:data:changeinfo")
    @Transactional(rollbackFor=Exception.class)
    public Object changeInfo(@RequestBody Map<String, String> roleInfo){
        Integer roleId = Integer.parseInt(roleInfo.get("hidId"));
        SysRole sysRole = new SysRole();
        sysRole.setRoleId(roleId);
        sysRole.setRoleName(roleInfo.get("roleName"));
        sysRole.setRoleRemarks(roleInfo.get("roleRemarks"));
        sysRole.setIsSys(roleInfo.get("isSys"));
        int num = iSysRoleService.changeRoleInfo(sysRole);
        if(num<=0){
            throw new SystemException(StatusCode.FAILED,"修改角色数据失败！");
        }
        String permission = "permissionId";
        if(roleInfo.get(permission) == null && "".equals(roleInfo.get(permission))){
            throw new SystemException(StatusCode.FAILED,"角色权限不能为空！");
        }
        List<String> result = new LinkedList<>();
        result.add(roleInfo.get("hidId"));
        num = iSysRolePermissionService.delSysRolePermission(result);
        if(num<=0){
            throw new SystemException(StatusCode.FAILED,"删除角色原权限失败！");
        }
        SysRolePermission sysRolePermission=new SysRolePermission();
        sysRolePermission.setRId(roleId);
        //获取修改页面权限ID字符串并循环赋值给权限关系表对象进行遍历插入
        String[] pName= roleInfo.get(permission).split(",");
        int i=0;
        while (i<=pName.length-1){
            String selectPname = pName[i];
            String insertPid = iSysPermissionService.getPidToPname(selectPname);
            if(insertPid!=null && !"".equals(insertPid)){
                sysRolePermission.setPId(Integer.parseInt(insertPid));
                num += iSysRolePermissionService.addSysRolePermission(sysRolePermission);
            }
            i++;
        }
        if(num <= 0){
            throw new SystemException(StatusCode.FAILED,"新增角色新权限失败！");

        }
        //清除redis菜单缓存
        yzCacheHelper.autoClearCache(num, YzCacheName.MENU_CACHE_NAME);
        //检查redis数据库发现shiro中还存在部分权限缓存需要删除
        yzCacheHelper.autoClearCache(num, YzCacheName.SHIRO_AUTO_PERMISSION_CACHE_NAME);
        return Urmf.success("修改角色数据内容", StatusCode.SUCCESS,"数据修改成功");
    }
    /**
     * 新增角色表数据
     * @param sysrole 角色对象
     * @return 成功状态
     */
    @ApiDesc(value = "新增SysRole数据",log = true)
    @RequestMapping("/addRole")
    @RequiresPermissions("api:role:data:add")
    @Transactional(rollbackFor=Exception.class)
    public  Object addSysRole(@RequestBody SysRole sysrole){
        SysUser user = (SysUser) SecurityUtils.getSubject().getPrincipal();
        sysrole.setCreateBy(user.getLoginName());
        if(iSysRoleService.check(sysrole)==1){
           throw new SystemException(StatusCode.FAILED,"角色重复！");
        }
        sysrole.setRoleId(iSysRoleService.newId());
        int num=iSysRoleService.addSysRole(sysrole);
        if(num <= 0 ){
            throw new SystemException(StatusCode.FAILED,"角色数据添加失败！");
        }
        SysRolePermission sysRolePermission=new SysRolePermission();
        sysRolePermission.setRId(sysrole.getRoleId());
        //获取新增页面权限ID字符串并循环赋值给权限关系表对象进行遍历插入
        String[] pId= sysrole.getPermission().split(",");
        //有效权限数量
        int perNum = 0;
        for(int i=0;i<=pId.length-1;i++){
            String selectPid = pId[i];
            String[] realPid=pId[i].split(":");
            if (realPid.length==4){
                perNum++;
                String insertPid = iSysPermissionService.getPid(selectPid);
                sysRolePermission.setPId(Integer.parseInt(insertPid));
                num += iSysRolePermissionService.addSysRolePermission(sysRolePermission);
            }
        }
        if(num < perNum){
            throw new SystemException(StatusCode.FAILED,"权限数据添加失败！");
        }
        return Urmf.success("新增Role数据", StatusCode.SUCCESS,"数据添加成功！");
    }

    /**
     * 删除角色表数据
     * @param roleInfo 角色ID
     * @return 成功状态
     */
    @ApiDesc(value = "删除Role数据",log = true)
    @DeleteMapping("/delRole")
    @RequiresPermissions("api:role:data:del")
    @Transactional(rollbackFor=Exception.class)
    public  Object delSysRole(@RequestBody Map<String, String> roleInfo){
        String roleId = roleInfo.get("roleId");
        List<String> result = Arrays.asList(roleId.substring(0,roleId.length()-1).split(","));
        int num ;
        num = iSysRoleService.delSysRole(result);
        if(num<=0){
            throw new SystemException(StatusCode.FAILED,"删除角色基表数据失败！");
        }
        //根据角色Id删除角色权限关系表数据
        num = iSysRolePermissionService.delSysRolePermission(result);
        if(num<=0){
            throw new SystemException(StatusCode.FAILED,"删除角色权限关系表数据失败！");
        }
        return Urmf.success("删除Role数据", StatusCode.SUCCESS,"成功删除角色相关数据！");
    }

    /**
     * 根据参数停用或者启用表数据
     * @param roleInfo hidId用户表主键  way 数据操作方式
     * @return 成功状态
     */
    @ApiDesc(value = "停用/启用Role数据",log = true)
    @PutMapping("/updateData")
    @RequiresPermissions("api:role:data:updatedata")
    public Object updateData(@RequestBody Map<String, String> roleInfo){
        Integer result = Integer.parseInt(roleInfo.get("hidId"));
        int num= iSysRoleService.updateRoleData(result,roleInfo.get("way"));
        if(num <= 0){
            return Urmf.fail("改变Role数据状态", StatusCode.FAILED,"操作失败！");
        }
        return Urmf.success("改变Role数据状态", StatusCode.SUCCESS,"修改状态成功！");

    }

    /**
     * 读取数据，为前端多选下拉提供data来源
     * @return 下拉数据json字符串
     */
    @ApiDesc(value = "获取角色下拉数据json字符串",log = true)
    @GetMapping("/getRolelist")
    @RequiresPermissions("api:role:data:getlist")
    public  String getPermissionslist(){
        JSONObject sysPermissionsJson=toolsUtil.getReturnData("role");
        List<SysRole> sysRoles = iSysRoleService.getSysRoleList();
        sysPermissionsJson.put("data",sysRoles);
        return sysPermissionsJson.toJSONString();
    }
}
